<template>
  <div class="setting-wrapper" v-loading.fullscreen.lock="loading">
    <ul class="setting-top">
      <li class="top-left">
        <el-button icon="el-icon-back" type="text" @click="back"
        >返回</el-button
        >
        <span>
          {{ linkcInfosName }}
        </span>
      </li>
      <li class="top-center" @click="topClick">
        <span
          v-for="item in settingTop"
          :class="item.index === topIndex ? 'active' : ''"
          :key="item.index"
          :data-index="item.index"
        >{{ item.label }}</span
        >
      </li>
      <li class="top-right">
        <el-button @click="save" plain>保存</el-button>
        <el-button @click="release">发布</el-button>
      </li>
    </ul>
    <ul class="setting-bar">
      <li class="bar-left">组件配置（支持拖动、点击）</li>
      <li class="bar-center">手机效果展示</li>
      <li class="bar-right">规则配置</li>
    </ul>
    
    <div class="portal-form-design">
      <mform-design
        :mode="formDesignMode"
        :value="fields"
        @input="updateFields"
        :index="topIndex"
        :filterFields="filterFields"
        ref="formDesign"
      >
      </mform-design>
    </div>

  </div>
</template>

<script>
import draggable from 'vuedraggable'
/* api */
import { getDoorTypeFieldList, updateDoorTypeFieldList, updateDoorTypeFieldListDraft } from '@src/api/PortalApi.ts'
/* util */
import { getRootWindowInitData } from '@src/util/window'
import * as FormUtil from '@src/mform/util'
import { isEmpty } from '@src/util/type'
import qs from '@src/util/querystring'
import { randomString } from 'pub-bbx-utils'
import _ from 'lodash'
/* hooks */
import { useIMSetting } from '@hooks/setting/useIMSetting.ts'
import { usePortal } from '@hooks/portal/usePortal.ts';
/* vue */
import { computed } from 'vue'
/* mixin */
import { VersionControlIMMixin } from '@src/mixins/versionControlMixin'

import {
  getConfig
} from '@src/api/ProductV2Api';

/* constant */
const UserCenterField = {
  'id': null, 
  'fieldName': `field2${randomString()}`,
  'formType': 'userCenter',
  'displayName':'个人中心',
  'isNull': 1,
  'revisable': 1, 
  'visible': 1, 
  'isSearch': 0,
  'placeHolder':'', 
  'defaultValue': null,
  'isSystem': 0,
  'isAppShow': 0,
  'isHidden': 0,
  'isCommon': 0,
  'isPublic': 0,
  'isDragCommon': 0,
  'isOnceCommon': 0,
  'setting':{ 'backgroundUrl': '', background_picture: ''},
  'dragging':false
}

export default {
  name: 'decoration-view',
  mixins: [VersionControlIMMixin],
  inject: ['initData'],
  data() {
    return {
      topIndex: 1,
      settingTop: [
        { label: '门户首页', index: 1 },
        { label: '服务', index: 2 },
        // { label: '个人中心', index: 3 },
      ],
      homeFields: [],
      serviceFields: [],
      userFields: [],
      loading: false,
      backup: {
        homeFields: [],
        serviceFields: [],
        userFields: [],
      },
      filterFields: []
    }
  },
  computed: {
    fields() {
      if (this.topIndex == 1) {
        return this.homeFields
      }
      
      if (this.topIndex == 2) {
        return this.serviceFields
      }
      
      if (this.topIndex == 3) {
        return this.userFields
      }
      
      return []
    },
    rootWindowInitData() {
      return getRootWindowInitData()
    },
    tenantId() {
      return this.rootWindowInitData?.user?.tenantId || '7416b42a-25cc-11e7-a500-00163e12f748'
    },
    queryObject() {
      return qs.parse(window.location.search)
    },
    typeId() {
      return this.queryObject.id
    }
  },
  watch: {
    // 
  },
  setup() {
    const [IMSetting, IMEnabled] = useIMSetting()
    const [ linkcInfos, linkcInfosName ] = usePortal()
    const formDesignMode = computed(() => IMEnabled.value ? 'door' : 'base')
    
    return {
      linkcInfosName,
      IMSetting,
      IMEnabled,
      formDesignMode
    }
  },
  mounted() {
    this.getDoorTypeFieldList()
    this.isOpenRegisterCheck()
  },
  methods: {
    isOpenRegisterCheck() {
      getConfig({
        configCode: [
          'PRODUCT_REGISTRATION'
        ]
      }).then(res => {
        if(res.errorCode === 0) {
          let isOpenRegister = !!res?.data[0]?.isOpen
          if (!isOpenRegister) {
            this.filterFields.push('productRegister')
          }
        }
      })
    },
    buildFields(isClone) {
      let homeFields = FormUtil.toField(this.homeFields, 'homepage', this.typeId, isClone)
      let serviceFields = FormUtil.toField(this.serviceFields, 'service', this.typeId, isClone)
      let userFields = FormUtil.toField(this.userFields, 'personal', this.typeId, isClone)
      
      return homeFields.concat(serviceFields).concat(userFields)
    },
    getDoorTypeFieldList() {
      this.loading = true
      getDoorTypeFieldList({ tenantId: this.tenantId, typeId: this.typeId, draft: 1 })
        .then(result => {
          if (result.code == 200) {
            const data = (result?.data || []).filter(v => {
              // 不包含客服云版本时过滤在线客服字段
              if (v.formType == 'im') {
                return this._isShowIMModule
              }
              return v
            })
            this.initDoorTypeField(data);
            
          } else {
            this.$platform.alert(result.msg)
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    // 初始化各个模块的数据内容
    initDoorTypeField(data) {
      let homeFields = data.filter(field => field.modular == 'homepage')
      let serviceFields = data.filter(field => field.modular == 'service')
      let userFields = data.filter(field => field.modular == 'personal')
      
      this.homeFields = FormUtil.initializeSetting(homeFields)
      this.serviceFields = FormUtil.initializeSetting(serviceFields)
      userFields = FormUtil.initializeSetting(userFields)

      let isHasUserCenterField = userFields.some(field => field.formType == 'userCenter')
      if (isHasUserCenterField) {
        this.userFields = userFields
      } else {
        this.userFields = [UserCenterField].concat(userFields)
      }
      
      this.backup.homeFields = _.cloneDeep(this.homeFields)
      this.backup.serviceFields = _.cloneDeep(this.serviceFields)
      this.backup.userFields = _.cloneDeep(this.userFields)
    },
    updateDoorTypeFieldList(isRelease = true) {
      const params = {
        tenantId: this.tenantId,
        doorTypeFieldVOS: this.buildFields(),
        typeId: this.typeId
      }

      if (isRelease) {
        updateDoorTypeFieldList(params)
          .then(result => {
            if (result.success) {
              this.$platform.notification({
                title: '成功',
                type: 'success',
                message: '发布成功，请前往移动端自助门户查看',
              })
              sessionStorage.removeItem('doorTypeFieldVOS');
              // window.location.reload()
              window.history.back();
            } else {
              this.$platform.notification({
                title: '发布失败',
                type: 'error',
                message: result.message,
              })
            }
          })
      } else {
        updateDoorTypeFieldListDraft(params)
          .then(result => {
            if (result.success) {
              this.$platform.notification({
                title: '成功',
                type: 'success',
                message: '保存成功',
              })
              sessionStorage.removeItem('doorTypeFieldVOS');
              window.location.reload()
            } else {
              this.$platform.notification({
                title: '保存失败',
                type: 'error',
                message: result.message,
              })
            }
          })
      }
    },
    validateFields(isRelease = true) {
      this.$refs.formDesign.changeSettingComponentIsValidateAll()
      
      let homeFieldsMessage = this.validateHomeFields()
      if (!isEmpty(homeFieldsMessage)) {
        this.topIndex = 1
        const field = homeFieldsMessage?.[0]?.field
        field && this.$refs.formDesign.chooseField(field)
        return 
      }
      
      let serviceFieldsMessage = this.validateServiceFields()
      if (!isEmpty(serviceFieldsMessage)) {
        this.topIndex = 2
        const field = serviceFieldsMessage?.[0]?.field
        field && this.$refs.formDesign.chooseField(field)
        return
      }
      
      let userFieldsMessage = this.validateUserFields()
      if (!isEmpty(userFieldsMessage)) {
        this.topIndex = 3
        const field = userFieldsMessage?.[0]?.field
        field && this.$refs.formDesign.chooseField(field)
        return
      }

      this.updateDoorTypeFieldList(isRelease)
    },
    validateHomeFields() {
      let homeFields = this.homeFields
      // 表单字段格式校验
      let message = FormUtil.validate(homeFields)
      if (!FormUtil.notification(message, this.$createElement)) {
        FormUtil.setFieldError(message)
        return message
      }
      
      return []
    },
    validateServiceFields() {
      let serviceFields = this.serviceFields
      // 表单字段格式校验
      let message = FormUtil.validate(serviceFields)
      if (!FormUtil.notification(message, this.$createElement)) {
        FormUtil.setFieldError(message)
        return message
      }
      
      return []
    },
    validateUserFields() {
      let userFields = this.userFields
      // 表单字段格式校验
      let message = FormUtil.validate(userFields)
      if (!FormUtil.notification(message, this.$createElement)) {
        FormUtil.setFieldError(message)
        return message
      }
      
      return []
    },
    // 保存
    async save() {
      this.validateFields(false)
    },
    // 发布
    async release() {
      this.validateFields();
    },
    // 切换配置
    topClick(e) {
      if (e.target.nodeName.toLowerCase() !== 'span') return
      
      const index = parseInt(e.target.dataset.index)
      if (this.topIndex === index) return
      
      if (this.topIndex == 1) {
        let homeFieldsMessage = this.validateHomeFields()
        if (!isEmpty(homeFieldsMessage)) {
          this.topIndex = 1
          const field = homeFieldsMessage?.[0]?.field
          field && this.$refs.formDesign.chooseField(field)
          return 
        }
      }
      
      if (this.topIndex == 2) {
        let serviceFieldsMessage = this.validateServiceFields()
        if (!isEmpty(serviceFieldsMessage)) {
          this.topIndex = 2
          const field = serviceFieldsMessage?.[0]?.field
          field && this.$refs.formDesign.chooseField(field)
          return
        }
      }
      
      if (this.topIndex == 3) {
        let userFieldsMessage = this.validateUserFields()
        if (!isEmpty(userFieldsMessage)) {
          this.topIndex = 3
          const field = userFieldsMessage?.[0]?.field
          field && this.$refs.formDesign.chooseField(field)
          return
        }
      }
      
      this.topIndex = index
      this.$refs.formDesign.resetCurrentField()
    },
    async back() {
      if (
        _.isEqual(this.homeFields, this.backup.homeFields)
        && _.isEqual(this.serviceFields, this.backup.serviceFields)
        && _.isEqual(this.userFields, this.backup.userFields)
      ) {
        window.history.back()
        return
      }
      
      this.$confirm('部分组件的修改还未保存，确定要返回吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        
        window.history.back()
        
      }).catch(() => {
        // 
      })
      
    },
    updateFields(fields) {
      if (this.topIndex == 1) {
        this.homeFields = fields
        return
      }
      
      if (this.topIndex == 2) {
        this.serviceFields = fields
        return
      }
      
      if (this.topIndex == 3) {
        this.userFields = fields
        return
      }
    }
  },
  components: {
    draggable
  },
}
</script>

<style lang="scss" scoped>
.setting-wrapper {
  ul {
    margin-bottom: 0;
  }
  .setting-top {
    height: 50px;
    color: #fff;
    background: linear-gradient(270deg, $color-primary-light-4, $color-primary-light-6);
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding-left: 0;

    .top-left {
      padding-left: 20px;
      display: flex;

      .el-button--text {
        color: #fff !important;
      }

      ::v-deep .el-input {
        height: 50px;
        margin-left: 10px;
        border-left: 1px solid #fff;
      }

      ::v-deep .el-input__inner {
        background: none;
        border: none;
        color: #fff !important;
        font-size: 16px;
        border-bottom: 1px dashed #fff;
        margin-left: 10px;
        margin-top: 5px;
      }

      ::v-deep input::-webkit-input-placeholder,
      textarea::-webkit-input-placeholder {
        color: #eee;
      }
      ::v-deep input:-moz-placeholder,
      textarea:-moz-placeholder {
        color: #eee;
      }
      ::v-deep input::-moz-placeholder,
      textarea::-moz-placeholder {
        color: #eee;
      }
      ::v-deep input:-ms-input-placeholder,
      textarea:-ms-input-placeholder {
        color: #eee;
      }
    }

    .top-center {
      font-size: 16px;
      position: absolute;
      left: 50%;
      margin-left: -240px;
      span {
        display: inline-block;
        width: 160px;
        height: 50px;
        line-height: 50px;
        text-align: center;
        cursor: pointer;
        position: relative;
      }
      .active {
        background-color: rgba(0, 0, 0, 0.1);
      }
      .active:after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 50%;
        transform: translateX(-50%);
        display: block;
        width: 0;
        height: 0;
        border-left: 5px solid transparent;
        border-right: 5px solid transparent;
        border-bottom: 8px solid #f5f5f5;
      }
    }

    .top-right {
      padding-right: 10px;
      ::v-deep .el-button {
        color: $color-main;
      }
    }

    ::v-deep .el-button--text {
      color: #fff;
      font-size: 16px;
    }
  }
  .setting-bar {
    height: 40px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    color: #8c8c8c;
    padding-left: 20px;
    background-color: $color-primary-light-1;
    position: relative;
  }
  .setting-bottom {
    padding: 12px;
    height: calc(100vh - 90px);
    display: flex;

    .btm-item {
      height: 100%;
      border-radius: 4px;
      padding: 12px;

      .btm-left-title {
        font-size: 14px;
        font-weight: bold;
      }
    }
    .btm-left {
      width: 25%;
      background-color: #fafafa;
      margin-right: 12px;

      .drag-left {
        display: flex;
        flex-wrap: wrap;

        .drag-left-item {
          width: 30%;
          height: 80px;
          text-align: center;
          font-size: 12px;
          color: $text-color-regular;
          margin-right: 3%;
          cursor: all-scroll;
          box-sizing: border-box;
          border: 1px solid transparent;
          i {
            font-size: 34px;
            color: $color-primary;
          }
        }
        .forbid {
          i {
            color: $text-color-gray;
          }
        }
        .drag-left-item:hover {
          background-color: #fff;
          border: 1px solid $color-border-l1;
          border-radius: 4px;
        }
        .chosen {
          background-color: #fff;
          border: 1px solid $color-border-l1;
          border-radius: 4px;
        }
        .ghost {
          background-color: $bg-color-l2 !important;
          i {
            color: $text-color-gray;
          }
        }
      }
    }
    .btm-right {
      width: 25%;
      min-width: 300px;
      background-color: #fafafa;
      margin-left: 12px;
    }
    .btm-center {
      flex-grow: 1;
      padding: 12px 0;
      position: relative;
      overflow: hidden;

      .btm-center-phone {
        width: 320px;
        height: 100%;
        overflow-y: auto;
        margin: 0 auto;
        padding: 8px;
        border: 1px solid $color-border-l1;
        border-radius: 8px;
        background-color: $bg-color-l2;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.2);

        .drag-right-wrap {
          height: 100%;

          .drag-right {
            display: block;
            height: 100%;
            position: relative;
          }
        }
      }
      .btm-center-name {
        cursor: pointer;
        position: absolute;
        top: 12px;
        left: calc(50% + 165px);
        max-width: 116px;
        background-color: #fff;
        border: 1px solid $color-border-l1;
        border-radius: 4px;
        padding: 5px;
      }
    }
  }
}
</style>

<style lang="scss">
.top-left {
  & > span {
    margin-left: 12px;
    display: inline-flex;
    align-items: center;
    font-size: 16px;
  }
}
.portal-form-design {
  height: calc(100% - 90px);
  .form-design {
    padding-top: 12px;
    padding-left: 12px;
  }
  .form-design-setting {
    width: 430px;
  }
  .form-setting-panel {
    padding: 0;
  }
}

.setting-wrapper {
  .setting-bar {
    text-align: center;
  }
  .bar-left {
    width: 192px;
  }
  .bar-right {
    width: 430px;
  }
  .setting-top {
    .top-left {
      line-height: 36px;
      button {
        position: relative;
        display: flex;
        width: 66px;
        &::after {
          content: "";
          position: absolute;
          top: -8px;
          right: 0;
          height: 50px;
          width: 1px;
          background-color: #f5f5f5;
        }
      }
      span {
        max-width: 240px;
        @include text-ellipsis;
        display: inline-block;
      }
    }
  }
}
</style>
